package com.app.scale.record;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.scale.R;
import com.app.scale.basis.BasisActivity;
import com.app.scale.basis.Constants;
import com.app.scale.bean.GoodsListBean;
import com.app.scale.bean.GoodsListData;
import com.app.scale.bean.LoginBean;
import com.app.scale.bean.RecordListData;
import com.app.scale.bean.UserInfoBean;
import com.app.scale.bean.UserInfoList;
import com.app.scale.greendao.GreenDaoUtils;
import com.app.scale.scale.ScaleActivity;
import com.app.scale.scale.ScalePresenterImpl;
import com.app.scale.util.MyUtils;
import com.app.scale.util.ReadCardUtils;
import com.app.scale.view.MyEditText;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.DialogUtils;
import my.LogUtil;
import my.MathUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 茶青统计
 */
public class  RecordInfoActivity extends BasisActivity implements RecordView{

    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private GoodsListBean mListBean;

    RecordListData parentBean;
    RecordPresenter presenter;
    boolean isChange =false;

    @BindView(R.id.text_wt)
    TextView text_wt;
    UserInfoBean curJiJiaYuan; // 计价员的bean


    @Override
    public void initViews() {
        setContentView(R.layout.record_info_activity);
        setTitle("交易明细");
        setTitleBg(R.color.base_blue);
        setTitleLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isChange = true){
                    setResult(RecordListActivity.WARNLISTRESULT);
                }
                finish();
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);

        setTitleRightButton(R.mipmap.icon_save_white, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isChange = true;
                presenter.toChange(parentBean,mListBean);
            }
        });

        setTitleRightButton2(R.mipmap.icon_printer, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.toPrint(parentBean,mListBean);
            }
        });

        presenter = new RecordPresenterImpl(this,this);

        presenter.getIWeigh();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        Bundle bundle = getIntent().getExtras();

        parentBean = (RecordListData) bundle.getSerializable("data");
        if(parentBean == null){
            showToast("数据为空");
            finish();
            return;
        }
        if(LoginBean.getInstance().canJijia()){
            curJiJiaYuan = UserInfoBean.getAdminInfo();
        }

        mListBean = new GoodsListBean();
        setListView();

        getList();
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }


    private void getList() {
        MyParams params = new MyParams();
        showProgress();
        params.put("aid", LoginBean.getInstance().getAid());
        params.put("tid", parentBean.getTid());

        MyHttpUtils.get(Constants.URL_LEAF_GET_LEAF_BY_ID, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        GoodsListBean goodsListBean = (GoodsListBean) result;
                        mListBean.addListBean(goodsListBean);
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        mListBean.getList().clear();
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        if (isFinishing()) return;
                        dismissProgress();
                    }
                },
                0, GoodsListBean.class);

    }

    @Override
    public void printMessage(String message) {
        showToast(message);
    }

    @Override
    public void printFinish() {

    }

    @Override
    public void httpSuccess() {
        getList();
    }

    @Override
    public void showWeight(String value) {
        text_wt.setText(value);
    }


    public class MyAdapterList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        public MyAdapterList() {
        }

        //创建新View，被LayoutManager所调用
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            if (viewType == TYPE_CONTENT) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.record_info_list_item, viewGroup, false);
                return new ViewHolder(view);
            } else {
                View viewFoot = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.record_info_foot, viewGroup, false);
                return new FootHolder(viewFoot);
            }
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
            if (viewHolder instanceof ViewHolder) { // 内容
                ((ViewHolder) viewHolder).bind(position);
            } else { // 尾部
                ((FootHolder) viewHolder).bind(position);
            }
        }

        private static final int TYPE_CONTENT = 0, TYPE_FOOTER = 1;

        @Override
        public int getItemViewType(int position) {
//            return super.getItemViewType(position);
            return (position == (getItemCount() - 1)) ? TYPE_FOOTER : TYPE_CONTENT;
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : (mListBean.getList().size() + 1);
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_gna)
            public TextView text_gna;
            @BindView(R.id.text_gwt)
            public TextView text_gwt;
            @BindView(R.id.edit_gpr)
            public MyEditText edit_gpr;
            @BindView(R.id.edit_pwt)
            public EditText edit_pwt;
            @BindView(R.id.text_sje)
            public TextView text_sje;
            @BindView(R.id.add_btn)
            public TextView add_btn;
            @BindView(R.id.text_accumulation)
            public TextView text_accumulation;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                edit_pwt.removeTextChangedListener(mPwtWatcher);
                edit_pwt.addTextChangedListener(mPwtWatcher);


                edit_gpr.removeTextChangedListener(mGprWatcher);
                edit_gpr.addTextChangedListener(mGprWatcher);
            }

            public void bind(int position) {
                GoodsListData data = mListBean.getList().get(position);
                MyUtils.setNotNullText(text_gna,""+data.getGna());
                edit_gpr.setText(data.getGpr());
                if(curJiJiaYuan == null){
                    edit_gpr.setEnabled(false);
                }else {
                    edit_gpr.setEnabled(true);
                }
                MyUtils.setNotNullText(text_gwt,""+data.getGwt()+"斤");
                MyUtils.setNotNullText(text_sje,""+data.getSje()+"元");
                MyUtils.setNotNullText(text_accumulation,""+data.getAcc());
                edit_pwt.setText(data.getPwt());
                list_item.setTag(data);
                add_btn.setTag(data);

            }

            TextWatcher mPwtWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    GoodsListData data = mListBean.getList().get(position);
                    if(s.toString().equals("") || TextUtils.isEmpty(s.toString()) || "null".equals(s.toString())){
                        data.setPwtAndNotify("0");
                    }else {
                        data.setPwtAndNotify(s.toString());
                    }

                }
            };
            TextWatcher mGprWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = getAdapterPosition();
                    GoodsListData data = mListBean.getList().get(position);
                    if(s.toString().equals("") || TextUtils.isEmpty(s.toString()) || "null".equals(s.toString())){
                        data.setGprAndNotify("0");
                    }else {
                        data.setGprAndNotify(s.toString());
                    }
                }
            };

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {
                GoodsListData data = (GoodsListData) v.getTag();
                if(curJiJiaYuan != null) return;
                DialogUtils.showEditNumberDialog(mContext,"提示","请输入计价员卡号", "确定", new DialogUtils.TextResult() {
                    @Override
                    public void resultText(String text) {
                        getUserInfoByCardNo(text);
                    }
                });

            }
            @OnClick(R.id.add_btn)
            public void onAddClick(View v) {
                GoodsListData data = (GoodsListData) v.getTag();
                if(TextUtils.isEmpty(edit_pwt.getText().toString())){
                    edit_pwt.setText("0");
                }
                edit_pwt.setText(MathUtils.add(data.getPwt(),presenter.getScaleWeight()));
            }

        }

        // 尾部
        public class FootHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_all_sje)
            public TextView text_all_sje;
            @BindView(R.id.text_all_gwt)
            public TextView text_all_gwt;

            public FootHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);

            }

            public void bind(int position) {
                text_all_sje.setText(mListBean.getAllSje()+"元");
                text_all_gwt.setText(mListBean.getAllWeight()+"斤");
            }


            @OnClick(R.id.list_item)
            public void onBtnSave() {

            }

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.closeIWeigh();
        presenter.ClosePort();
    }



    @Override
    public void onBackPressed() {
        if(isChange = true){
            setResult(RecordListActivity.WARNLISTRESULT);
        }
        super.onBackPressed();
    }


    public void getUserInfoByCardNo(String cardNo){
        MyParams params = new MyParams();
        params.put("cardno", cardNo);
        showProgress();
        MyHttpUtils.get(Constants.URL_SELECT_BY_CAR_NO, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                if(mContext.isFinishing())return;
                UserInfoList userInfoList = (UserInfoList) result;
                if(userInfoList.isJijiayuan()){
                   curJiJiaYuan = userInfoList.getList().get(0);
                   mAdapter.notifyDataSetChanged();
                }else {
                    showToast("此卡非计价员或管理员");
                    curJiJiaYuan = null;
                }

            }

            @Override
            public void onFailure(int httpWhat, Object result) {
                if(mContext.isFinishing())return;
                showToast("无效卡！");
                curJiJiaYuan = null;
            }

            @Override
            public void onFinish(int httpWhat) {
                if(mContext.isFinishing())return;
                dismissProgress();
            }
        }, 0, UserInfoList.class);
    }


}
